﻿@page "/counter"
@using RabbitMQ.Client;
@using RabbitMQ.Client.Events;
@using System.Text;

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="aa">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount() {
        currentCount++;
    }
    ConnectionFactory factory = new() {
            HostName = "192.168.5.168",
            UserName = "admin",
            Password = "123"
        };
    private IConnection connection;
    private IModel channel;
    private void aa() {
        connection = factory.CreateConnection();
        channel = connection.CreateModel();
        //输入1，那如果接收一个消息，但是没有应答，则客户端不会收到下一个消息
        channel.BasicQos(0, 1, false);

        //定义一个EventingBasicConsumer消费者
        var consumer = new EventingBasicConsumer(channel);
        //接收到消息时触发的事件
        consumer.Received += (model, ea) => {
            var content = string.Empty;
            bool? result = null;
            try {
                var body = ea.Body;
                content = Encoding.UTF8.GetString(body.ToArray());
                if (result ?? true) {
                    channel.BasicAck(ea.DeliveryTag, false);
                }
                //LogWrite("信息", content);
            } catch (Exception ex) {
                var a = "";
            }

        };
        // LogWrite("信息", "开始监听");
        //调用消费方法 queue指定消费的队列，autoAck指定是否自动确认，consumer就是消费者对象
        channel.BasicConsume(queue: "log", autoAck: false, consumer: consumer);
        currentCount++;
    }
}
